﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using EzDesk.Core.Model;
using EzDesk.Core.Interface;
using EzDesk.Core.ServiceImpl.Repositories;
using EzDesk.Utility.Json;
using EzDesk.Utility.Log;
using EzDesk.Utility.Generic;
using Microsoft.Practices.Unity;

namespace EzDesk.Core.ServiceImpl.Services
{
    public class CoreAppService : ContainerAccessorBase, ICoreAppService
    {
        //todo: 在这个地方对应用程序的Core服务调用进行安全验证

        private ICoreService _coreService;
        private IMembershipService _membershipService;
        private const string FeedTemplateStr_core_newhireupdate = "core_newHireUpdate";

        public CoreAppService()
        {
            this._coreService = Container.Resolve<ICoreService>();
            this._membershipService = Container.Resolve<IMembershipService>();
        }

        public CoreAppService(ICoreService coreService)
        {
            this._coreService = coreService;

            LogEx.TRACE("CoreService - CoreAppService", "初始化CoreAppService");
        }


        public UserProfile GetUserProfileByUserName(string userName)
        {
            return _coreService.GetUserProfileByUserName(userName);
        }

        public UserProfile GetUserProfileById(Guid userId)
        {
            return _coreService.GetUserProfileById(userId);
        }

        public void ChangeUserDept(Guid userId, Guid deptId)
        {
            _coreService.ChangeUserDept(userId, deptId);
        }

        public void ChangeUserPosition(Guid userId, Guid positionId)
        {
            _coreService.ChangeUserPosition(userId, positionId);
        }

        public IList<SimpleUser> GetSimpleUserInfos(string memberstring)
        {
            return _coreService.GetSimpleUserInfos(memberstring);
        }


        public IList<UserProfile> GetUserProfiles(string memberstring)
        {
            return _coreService.GetUserProfiles(memberstring);
        }

        public IList<Dept> GetAllDepts()
        {
            return _coreService.GetAllDepts();
        }


        public Guid? CreateNewUser(UserProfile newUserProfile, string newPassword)
        {
            // 先确保新的用户名不重复

            var existUser = _coreService.GetUserProfileByUserName(newUserProfile.UserCode);
            if (existUser != null)
            {
                LogEx.TRACE("CoreAppService - CreateNewUser", "用户名重复");
                return null;
            }

            var userProfile = _coreService.CreateEmptyUserProfile(newUserProfile.UserCode);
            _membershipService.CreateUser(userProfile.UserCode, newPassword);

            newUserProfile.Id = userProfile.Id;
            newUserProfile.UserCode = userProfile.UserCode;
  

            _coreService.UpdateUserProfile(newUserProfile);

            var dept = _coreService.GetDeptById(newUserProfile.DeptId.GetValueOrDefault());

            var feedData = new Dictionary<string, string>
                               {
                                   {"actorName",newUserProfile.Name},
                                   {"deptName", dept.DeptName}
                               };
            
            SendFeed(
                FeedTemplateStr_core_newhireupdate,
                JsonHelper.ConvertToJson(feedData),
                "everyone", null, null, true
                );

            return newUserProfile.Id;
        }


        public void UpdateUserProfile(UserProfile userProfile)
        {
            _coreService.UpdateUserProfile(userProfile);
        }

        public void ChangePassword(Guid userId, string oldPassword, string newPassword)
        {
            var user = _coreService.GetSimpleUserById(userId);
            _membershipService.ChangePassword(user.UserName, oldPassword, newPassword);
        }

        public SimpleUser GetSimpleUserInfoByUserName(string userName)
        {
            return _coreService.GetSimpleUserInfoByUserName(userName);
        }

        public IList<SimpleUser> GetAllUsersByMemberString(string memberString)
        {
            return _coreService.GetAllUsersByMemberString(memberString);
        }
        public IDictionary<Guid, string> GetChildrenByMemberString(string memberString)
        {
            return _coreService.GetChildrenByMemberstring(memberString);
        }



        public IList<Group> GetAllSystemGroups()
        {
            return _coreService.GetAllSystemGroups();
        }


        public void UpdateFeedData(Guid feedId, string newFeedData)
        {
            _coreService.UpdateFeedData(feedId, newFeedData);
        }




        public SimpleUser GetSimpleUserById(Guid userId)
        {
            return _coreService.GetSimpleUserById(userId);
        }


        public void SetFeedsIsAvailable(string feedIdStrs, string memberString, bool isAvailable)
        {
            var feedIdArray = feedIdStrs.Split(',');
            IList<FeedStatus> feedStatus = (from id in feedIdArray
                                            where !string.IsNullOrEmpty(id)
                                            select new FeedStatus()
                                                       {
                                                           FeedId = new Guid(id),
                                                           IsAvailable = isAvailable,
                                                           IsMark = null,
                                                           IsRead = null,
                                                       }).ToList();
            _coreService.UpdateFeedStatus(feedStatus, memberString);
        }
        public void SetFeedIsAvailable(Guid feedId, string memberString, bool isAvailable)
        {
            SetFeedsIsAvailable(feedId.ToString(), memberString, isAvailable);
        }

        public Group GetGroupById(Guid groupId)
        {
            return _coreService.GetGroupById(groupId);
        }

        public IList<Group> GetGroups(string groupIdStrs)
        {
            return _coreService.GetGroups(groupIdStrs);
        }

        public void UpdateFeedsData(string updateFeeds, string updateFeedData)
        {
            _coreService.UpdateFeedData(updateFeeds, updateFeedData);
        }

        public void UpdatePersonalFeedData(Guid feedId, string memberstring, string feedDataEx)
        {
            _coreService.UpdatePersonalFeedData(feedId, memberstring, feedDataEx);
        }

        public Group GetSystemGroup(string groupName)
        {
            return _coreService.GetSystemGroup(groupName);
        }


        public Group GetGroupByName(string groupName)
        {
            return _coreService.GetGroupByName(groupName);
        }


        public bool UserHasPermission(string permissionStr, Guid userId)
        {
            return _coreService.UserHasPermission(permissionStr, userId);
        }

        public bool GroupHasPermission(string permissionStr, Guid groupId)
        {
            return _coreService.GroupHasPermission(permissionStr, groupId);
        }




        public void UpdateHeadIcon(Guid userId, byte[] iconData, string iconType)
        {
            _coreService.UpdateHeadIcon(userId, iconData, iconType);
        }

        public ImageData GetHeadIcon(Guid userId)
        {
            return _coreService.GetHeadIcon(userId);
        }

        public void SetFeedRecord(Guid identity, string templateName, string memberstring, Guid feedId, string ignoreUsers)
        {
            _coreService.SetFeedRecord(identity, templateName, memberstring, feedId, ignoreUsers);
        }

        public string GetFeedRecord(Guid identity, string templateName, string userId)
        {
            return _coreService.GetFeedRecord(identity, templateName, userId);
        }

        #region [ ContainerAccessor Members ]
        protected override IUnityContainer buildContainer()
        {
            // 初始化容器
            return new UnityContainer()
                .RegisterType<IOperationProperties, WebOperationProperties>()

                .RegisterInstance(Membership.Provider)
                .RegisterType<IMembershipService, AccountMembershipService>()

                .RegisterInstance(new EzDeskDataContext(), new ContainerControlledLifetimeManager())
                .RegisterType<ICoreService, CoreService>();

        }
        #endregion




        public void UpdatePersonalFeedType(Guid feedId, string memberstring, string feedTypeStr)
        {
            _coreService.UpdatePersonalFeedType(feedId, memberstring, feedTypeStr);
        }


        public Guid SendFeed(string templateName, string feedData, string memberString, Guid? senderId, string ignoreUsers, bool isAvailable)
        {
            return _coreService.SendFeed(
                templateName, feedData, memberString,
                DateTime.Now.AddDays(10), /* todo: 根据feed类型等参数来研究有效期的问题 */
                senderId, ignoreUsers, isAvailable);
        }
    }
}
